<template>
  <div class="wrap" v-loading="pageLoading">
    <div class="header-btn">
      <div>{{ title }}</div>
      <div>
        <el-button v-if="operateFlag != 'DETAIL'" type="primary" @click="confirm">确认</el-button>
        <el-button plain type="info" @click="goBack">返回</el-button>
      </div>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="130px"
             style="position: relative">
      <div class="g-card" style="padding-bottom: 16px">
        <div class="title-header">基础信息</div>

        <el-form-item label="链接名称：" prop="linkName">
          <div v-if="operateFlag == 'DETAIL'">{{ form.linkName }}</div>
          <el-input v-else v-model="form.linkName" placeholder="请输入链接名称" popper-class="minWidth-inp"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="页面标题：" prop="pageTitle">
          <div v-if="operateFlag == 'DETAIL'">{{ form.pageTitle }}</div>
          <el-input v-else v-model="form.pageTitle" placeholder="请输入页面标题" popper-class="minWidth-inp"
                    style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="获客渠道：" prop="drainagePlatform">
          <template v-if="operateFlag == 'DETAIL'">
               {{ showDrainagePlatform }}
          </template>
          <el-cascader v-else v-model="form.drainagePlatform" :multiple="false" :options="sourceIdList"
                       :show-all-levels="false" clearable filterable
                       placeholder="请选择获客渠道"
                       style="width: 400px"></el-cascader>
        </el-form-item>
      </div>
      <div class="g-card" style="padding-bottom: 16px;margin-top: 18px">
        <div class="title-header">获客方式</div>
        <el-row :gutter="24" style="width: 100%">
          <el-col :span="16">
            <el-form-item label="引流类型：" prop="drainageType" style="padding-bottom: 0">
              <template v-if="operateFlag == 'DETAIL'">
                <div v-for="item in radios" :key="item.dictValue">
                  {{ item.dictValue === form.drainageType ? item.dictLabel : '' }}
                </div>
              </template>
              <el-radio-group v-else v-model="form.drainageType" :disabled="$route.query.operateFlag == 'EDIT'"
                              @change="changRadio">
                <el-radio v-for="item in radios" :key="item.dictValue" :label="item.dictValue">{{
                    item.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :key="form.drainageType" :label="form.drainageType != 3 ? '关联活码：' : '链接地址：'"
                          :prop="form.drainageType != 3 ? '' : 'linkContent'" style="padding-bottom: 0">
              <NormalQrCode v-if="form.drainageType != 3" ref="normalQrCode" :codeInfo="codeParams"
                            :codeInfoList="form.drainageType == '1' ? codeInfoListA : codeInfoListB"
                            :disabled="operateFlag == 'DETAIL'"
                            :isChooseQrState="false" @deleteSeletedQrcode="deleteSeletedQrcode"
                            @selectedSure="qrCodeConfrim"/>

              <el-input v-else v-model="form.linkContent" placeholder="请输入" style="width: 400px"></el-input>
            </el-form-item>
            <el-form-item label="打标签" prop="labelState" v-if="form.drainageType != '3'">
              <el-switch v-model="form.labelState" style="margin-right: 8px" :disabled="$route.query.operateFlag == 'DETAIL'"></el-switch>
            </el-form-item>
            <el-form-item label="" v-if="form.labelState && form.drainageType != '3'" prop="label" >
              <div class="essInfo" v-if="operateFlag == 'DETAIL'">
                <el-tag v-for="(item, i) in form.label" :key="i" :closable="false" style="margin-bottom: 8px"
                        class="el-tag-tab-group" :style="'margin-left:10px'">
                  {{ item.groupName + '：' + item.tagName || item.tag }}
                </el-tag>
              </div>
              <tag-group v-else v-model="form.label"/>
            </el-form-item>
            <el-form-item label="直接显示活码" prop="isReveal" required v-if="form.drainageType != '3'">
              <div v-if="operateFlag == 'DETAIL'">{{ form.isReveal == '1' ? '是' : '否' }}</div>
              <el-radio-group v-else v-model="form.isReveal">
                <el-radio :label="'0'">否</el-radio>
                <el-radio :label="'1'">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="背景图" v-if="form.drainageType != '3'">
              <div class="upload">
                <el-upload
                  v-if="operateFlag != 'DETAIL'"
                  :before-upload="beforeUploadImg"
                  :show-file-list="false"
                  action
                  list-type="picture-card"
                >
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip" style="color: #CCCCCC">
                    上传图片大小不超过10MB
                  </div>
                </el-upload>
                <div v-for="(item, index) in imgs" :key="index" class="img" style="margin-left: 6px">
                  <img :src="item" width="100%"/>
                  <div class="imgPre">
                    <i class="el-icon-zoom-in" @click="dialogVisible = true, dialogImageUrl = item"></i>
                    <i class="el-icon-delete" @click="handleRemove(index)"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width: 200px">
            <div class="view" v-if="form.drainageType != '3'">
              <img alt="" class="view-phone" src="../../../../assets/image/image2.jpg">
              <img v-if="imgs && imgs.length > 0" :src="imgs[0]" alt="" class="view-bg">
              <img v-if="codeParams && codeParams.codeUrl" :src="codeParams.codeUrl" alt="" class="view-code">
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" append-to-body title="图片预览"
               width="600px">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
import {nameValidate} from "@/utils/validate";
import {addLink, detailLink, editLink} from "@/api/communityOperating/drainageLink";
import {uploadImgFile} from "@/api/communityOperating/fileManage";
import {getCapitalSource} from "@/api/placementStatistics";

export default {
  name: "AddDrainageLink",
  data() {
    return {
      title: "创建链接",
      operateFlag: '',
      codeTitle: "渠道活码",
      codeDialog: false,
      hkOpenFlagArr: [
        {dictLabel: "是", dictValue: "1",},
        {dictLabel: "否", dictValue: "0",}
      ],
      qrCodeForm: {}, // qr组件传值
      editCodeInfo: {},
      form: {
        linkName: "", // 链接名称
        linkContent: "", // 链接
        pageTitle: "", // 引导语
        drainagePlatform: "", // 引流平台
        drainageType: "1", // 引流类型
        businessId: "", // 关联的渠道活码
        businessType: "", // 1：渠道活码 2：群活码 3 员工码
        codeName: "", // 活码名称
        hkOpenFlag: '0', // 是否打开获客助手
        isReveal: '1',
        // mediaContentDetails: [],
        label: [],
        labelState: false,
      },
      options: [],
      radios: [],
      rules: {
        linkContent: [
          {required: true, message: '链接地址不能为空', trigger: 'blur'},
          {
            min: 10,
            max: 320,
            trigger: 'blur',
            message: '长度在 10 到 320 个字符',
          },
          {
            pattern: /((?:https?\:\/\/|http\.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)/i,
            message: '请输入以http://和https://开头的网址',
            trigger: 'blur',
          },
        ],
        linkName: [
          {
            required: true,
            validator: nameValidate("任务"),
            trigger: "change",
          },
        ],
        pageTitle: [
          {
            required: true,
            message: "请输入引导语",
            trigger: "blur",
          },
        ],
        drainagePlatform: [
          {
            required: true,
            message: "请选择引流平台",
            trigger: "change",
          },
        ],
        drainageType: [
          {
            required: true,
            message: "请选择引流类型",
            trigger: "change",
          },
        ],
      },
      codeParams: {
        qrState: '0',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: '',
        configId: '',
      },
      codeInfoListA: [
        {id: 1, name: '员工码', iconName: 'staff', isShow: true},
        {id: 2, name: '渠道活码', iconName: 'channel', isShow: true},
      ],
      codeInfoListB: [
        {id: 3, name: '群活码', iconName: 'qunhuoma', isShow: true},
      ],
      codeOpt: ['', '渠道活码', '群活码', '员工码'],
      imgs: [],
      dialogVisible: false,
      dialogImageUrl: '',
      sourceIdList: [],
      showDrainagePlatform: '',
      pageLoading: false,
    };
  },
  created() {
    // 引流平台
    this.getDicts("drainage_platform").then((res) => {
      if (res.code === 200) {
        this.options = res.data;
      }
    });
    // 引流类型
    this.getDicts("drainage_type").then((res) => {
      if (res.code === 200) {
        this.radios = res.data;
      }
    });
    getCapitalSource().then(res => {
      if (res.code == 200) {
        this.sourceIdList = res?.data?.map(item => {
          return {
            value: item.scrmGetGuestPlatId,
            label: item.scrmGetGuestPlatName,
            children: item?.children?.map(itm => {
              return {
                label: itm.scrmSourceName,
                value: itm.scrmGetGuestGourceId,
              }
            })
          }
        })
      }
    })
    this.detailLink();
  },
  methods: {
    // 切换按钮
    changRadio(val) {
      this.form.businessId = "";
      this.codeParams = {
        qrState: '0',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: '',
        configId: '',
      }
      console.log(this.form.drainageType, val);
      if (val == 3) {
        this.form.shortFlag = 1;
      } else {
        this.form.shortFlag = null;

        this.$refs.normalQrCode.clearSeletedItem();
      }
    },
    hkOpenFlagChang(val) {
      if (val == 1 && this.form.drainageType != '1') {
        this.form.drainageType = '1'
        this.changRadio()
      }
    },
    // 初始化查询
    detailLink() {
      if (this.$route.query.linkId) {
        this.title = this.$route.query.operateFlag == 'EDIT' ? "编辑链接" : "链接详情";
        detailLink({id: this.$route.query.linkId}).then((res) => {
          if (res.code === 200) {
            this.form = {
              ...res.data,
              drainagePlatform: res.data?.customerSource && res.data?.customerWay ? [res.data?.customerSource, res.data?.customerWay] : [],
              isReveal: String(res.data?.isReveal),
              labelState: res.data?.labelState == '1' ? true : false,
              label: JSON.parse(res?.data?.label)
            };
            this.imgs.push(res.data?.backGround)
            this.form.hkOpenFlag = this.form.hkOpenFlag.toString()
            // 不知道哪个傻蛋设置的编码顺序。。。（1渠道活码 2群活码 3 员工码），组件顺序：1员工码 2渠道活码 3 群活码
            this.codeParams = {
              qrState: '0',
              qrType: this.form.businessType == 1 ? 2 : this.form.businessType == 2 ? 3 : this.form.businessType == 3 ? 1 : '',
              activityName: res.data.codeName || '',
              codeUrl: res.data?.codeUrl || '',
              qrId: res.data?.businessId || '',
              configId: res.data?.configId
            }
            this.operateFlag = this.$route.query.operateFlag;
            if(res.data?.customerWay && res.data?.customerSource){
              let str = ''
              let arr = new Array()
              console.log(this.sourceIdList.find(item => item.value == res.data?.customerSource), 'sourceId')
              str += this.sourceIdList.find(item => item.value == res.data?.customerSource)?.label + '/'
              arr = this.sourceIdList.find(item => item.value == res.data?.customerSource)?.children
              str += arr.find(item => item.value == res.data?.customerWay)?.label
              this.showDrainagePlatform = str
            }
          }
        });
      } else {
        this.operateFlag = this.$route.query.operateFlag;
      }
    },
    // 确认
    confirm() {
      console.log(this.form)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // if (this.form.mediaContentDetails.length > 9) {
          //   this.$message.error("所有素材不能超过九个！")
          //   return
          // }
          if (this.form.drainageType != 3 && !this.codeParams.activityName) {
            this.$message.error("请选择二维码！")
            return
          }
          console.log(this.form.label, 'label' , this.form.labelState , !(this.form?.label && this.form?.label?.length > 0))
          if (this.form.labelState && !(this.form?.label && this.form?.label?.length > 0)) return this.$message.error('还未选择标签')
          let obj = JSON.parse(JSON.stringify(this.form))
          console.log(this.codeParams, 'codeParams')
          // 不知道哪个傻蛋设置的编码顺序。。。（1渠道活码 2群活码 3 员工码），组件顺序：1员工码 2渠道活码 3 群活码
          obj.businessType = this.codeParams.qrType == 1 ? 3 : this.codeParams.qrType == 2 ? 1 : this.codeParams.qrType == 3 ? 2 : 0;
          obj.codeName = this.codeParams.businessType != '3' ? this.codeParams.activityName : '';
          obj.businessId = this.codeParams.businessType != '3' ? this.codeParams.qrId : '0';
          obj.configId = this.codeParams.configId || ''
          obj.codeUrl = this.codeParams?.codeUrl || ''
          obj.labelState = this.form.labelState ? '1' : '0'
          obj.label = JSON.stringify(this.form.label)
          console.log(obj.codeUrl, this.codeParams.codeUrl, this.codeParams?.codeUrl, 'codeUrl')

          if (+this.codeParams.qrType == 1) {
            obj.weUserId = this.codeParams?.qrId || ''
          }

          if (this.form.drainagePlatform) {
            obj.customerSource = this.form.drainagePlatform[0]
            obj.customerWay = this.form.drainagePlatform[1]
          }
          if (this.imgs && this.imgs.length > 0) {
            obj.backGround = this.imgs[0]
          }
          if (this.form.drainageType == 3) obj.shortFlag = 1
          this.pageLoading = true
          // 编辑
          if (this.$route.query.linkId && this.$route.query.operateFlag == 'EDIT') {
            editLink({...obj}).then((res) => {
              if (res.code === 200) {
                this.$message.success("编辑成功");
                this.goBack();
              }
              this.pageLoading = false
            }).catch(() => {
              this.pageLoading = false
            })
          } else {
            obj.linkId = ''
            // 新增
            addLink({...obj}).then((res) => {
              if (res.code === 200) {
                this.$message.success("创建成功");
                this.goBack();
              }
              this.pageLoading = false
            }).catch(() => {
              this.pageLoading = false
            })
          }
        } else {
          this.$message.error("你还未录入完成，请核对后提交！");
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    // 删除二维码
    deleteSeletedQrcode() {
      this.codeParams.qrType = '';
      this.codeParams.activityName = '';
      this.codeParams.codeUrl = '';
      this.codeParams.qrId = '';
    },
    qrCodeConfrim(data) {
      if (data) {
        this.codeParams = {
          qrState: data.qrState,
          qrType: data.qrType,
          activityName: data.activityName,
          codeUrl: data.qrCode || data.codeUrl,
          qrId: data.qrId,
          configId: data.configId
        }
      }
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.form.mediaContentDetails = val;
    },
    // 图片上传
    async beforeUploadImg(img) {
      console.log(img)
      const type = ['image/png', 'image/jpg', 'image/gif', 'image/jpeg']
      const isJPG = type.includes(img.type)
      const isLt10M = img.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片支持jpg、png、gif格式!')
      } else if (!isLt10M) {
        this.$message.error('您上传的文件超过10MB!')
      } else {
        console.log(img, '====img')
        const formData = new FormData()
        formData.append('file', img)
        const {data} = await uploadImgFile(formData)
        console.log(data, 'data',)
        this.imgs = [window.globalConfig.IMAGE_API + data.url]
        console.log(this.imgs[0])
        this.form.photoName = data.fileName
        this.form.photoUrl = data.url
      }
    },
    // 图片删除
    handleRemove(index) {
      this.$confirm('是否确认删除所选图片？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imgs.splice(index, 1)
      }).catch()
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.img {
  position: relative;
  width: 148px;
  height: 148px;
  margin-right: 10px;

  img {
    height: 100%;
  }

  .imgPre {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(238, 238, 238, 0.4);
    display: flex;
    justify-content: space-around;
    align-items: center;
    opacity: 0;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 22px;
      color: #fff;
    }
  }
}

.upload {
  display: flex;
}

.view {
  width: 200px;
  height: 350px;
  position: relative;

  img {
    position: absolute;
  }
  .view-phone {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .view-bg{
    top: 7%;
    left: 8%;
    width: 85%;
    height: 86%;
  }
  .view-code{
    top: 106px;
    left: 50px;
    width: 100px;
    height: 100px;
  }
}
</style>
